import WebSocket from 'ws'
import { startRunner } from './index'
import { SOCKET_DATA_TYPES } from '../common/actionTypes'
import { addWsToStore, removeWsFromStore } from './wsStore'

const WebSocketServer = WebSocket.Server

export const registerWS = (server) => {
    let wss = new WebSocketServer({
        server: server
    })

    wss.on('connection', function (ws) {
        addWsToStore(ws)

        ws.on('message', async (messageString) => {
            const { type, data } = JSON.parse(messageString)
            switch (type) {
                case SOCKET_DATA_TYPES.RUN_PLAN: {
                    await startRunner(data)
                }
                default:
                    break
            }
        })

        ws.on('close', function () {
            removeWsFromStore(ws)
        })
    })
}